﻿Public Class xtf_LISTADOarticulo_
    Private dtt_componente_ As DataTable

    Public Overrides Sub IniciarLista()
        Try

            gdc_general.BringToFront()

            gdc_general.BeginUpdate()
            gdc_general.DataSource = dtt_DataTable
            'ulg_Lista.DisplayLayout.GroupByBox.Style = Infragistics.Win.UltraWinGrid.GroupByBoxStyle.Full

            'Creacion y carga de Cuentas
            dtt_DataTable.Columns.Add("Identificador (ID)")
            dtt_DataTable.Columns.Add("Código")
            dtt_DataTable.Columns.Add("Nombre")
            dtt_DataTable.Columns.Add("Descripcion")
            dtt_DataTable.Columns.Add("Rubro")
            dtt_DataTable.Columns.Add("En venta")
            dtt_DataTable.Columns.Add("Tipo")
            dtt_DataTable.Columns.Add("Unidad")
            dtt_DataTable.Columns.Add("Proveedor")
            dtt_DataTable.Columns.Add("Tipo costo")
            dtt_DataTable.Columns.Add("Fecha costo")
            dtt_DataTable.Columns.Add("Moneda")

            dtt_DataTable.Columns.Add("Costo", GetType(Decimal))

            gdv_general.PopulateColumns(dtt_DataTable)

            ''Grid de componentes--------------------------------------------
            dtt_componente_ = New DataTable
            dtt_componente_.Columns.Add("Identificador (ID)")
            dtt_componente_.Columns.Add("Código")
            dtt_componente_.Columns.Add("Nombre")
            dtt_componente_.Columns.Add("Descripcion")
            dtt_componente_.Columns.Add("Rubro")
            dtt_componente_.Columns.Add("En venta")
            dtt_componente_.Columns.Add("Tipo")
            dtt_componente_.Columns.Add("Unidad")
            dtt_componente_.Columns.Add("Proveedor")
            dtt_componente_.Columns.Add("Tipo costo")
            dtt_componente_.Columns.Add("Fecha costo")
            dtt_componente_.Columns.Add("Moneda")

            dtt_componente_.Columns.Add("Costo", GetType(Decimal))
            'gdc_componente_.BringToFront()
            gdc_componente_.BeginUpdate()
            gdc_componente_.DataSource = dtt_componente_
            gdv_componente_.PopulateColumns(dtt_componente_)
            FiltrarColumnas(gdc_componente_, gdv_componente_)
            gdv_componente_.BestFitColumns()
            gdc_componente_.EndUpdate()
            gdc_componente_.DataMember = Nothing

            ''---------------------------------------------------------------


            Dim obj_Articulo_ As New cls_articulo_
            If obj_Articulo_.CargarTodos Then
                For Each Articulo As cls_articulo_ In obj_Articulo_.Items
                    AgregarItem(Articulo)
                Next
            End If
            'ulg_Lista.DataBind()
            FiltrarColumnas()
            gdc_general.EndUpdate()

        Catch ex As Exception
            'Dim frmError As New frm_ErrorManager(ex.Message)
        End Try
    End Sub

    Public Function AgregarItem(ByRef Articulo As cls_articulo_) As DataRow
        Dim Row As DataRow = dtt_DataTable.NewRow
        Row("Identificador (ID)") = Articulo.idarticulo
        Row("Código") = Articulo.codigo
        Row("Nombre") = Articulo.nombre
        Row("Descripcion") = Articulo.descripcion
        Row("Rubro") = Articulo.articulorubro.ToString
        Row("En venta") = IIf(Articulo.enventa, "Sí", "No")
        Row("Tipo") = Articulo.tipo
        If Not IsNothing(Articulo.unidaddetalle) Then
            Row("Unidad") = Articulo.unidaddetalle.ToString
            Row("Costo") = Articulo.unidaddetalle.CValCargar(Articulo.costo)
        End If
        Row("Fecha costo") = ""
        Row("Proveedor") = ""
        Row("Moneda") = ""
        If Not IsNothing(Articulo.proveedor) Then
            Row("Proveedor") = Articulo.proveedor.ToString
            Dim tmp_proveedorarticulo As New cls_proveedorarticulo_
            If tmp_proveedorarticulo.BuscarUltimoXidarticuloXidproveedor(Articulo.idproveedor, Articulo.idarticulo) Then
                Row("Fecha costo") = tmp_proveedorarticulo.fecha.ToShortDateString
                Row("Moneda") = tmp_proveedorarticulo.moneda.ToString
            End If
        End If
        Row("Tipo costo") = EnumDescription(Articulo.tipocosto)

        dtt_DataTable.Rows.Add(Row)
        AgregarItemComposicion(Articulo)
        'ulg_Lista.Rows(ulg_Lista.Rows.Count - 1).Height = 19
        Return Row
    End Function

    Public Function AgregarItemComposicion(ByRef Articulo As cls_articulo_) As DataRow
        Dim Row As DataRow = dtt_componente_.NewRow
        Row("Identificador (ID)") = Articulo.idarticulo
        Row("Código") = Articulo.codigo
        Row("Nombre") = Articulo.nombre
        Row("Descripcion") = Articulo.descripcion
        Row("Rubro") = Articulo.articulorubro.ToString
        Row("En venta") = IIf(Articulo.enventa, "Sí", "No")
        Row("Tipo") = Articulo.tipo
        If Not IsNothing(Articulo.unidaddetalle) Then
            Row("Unidad") = Articulo.unidaddetalle.ToString
            Row("Costo") = Articulo.unidaddetalle.CValCargar(Articulo.costo)
        End If
        Row("Fecha costo") = ""
        Row("Proveedor") = ""
        Row("Moneda") = ""
        If Not IsNothing(Articulo.proveedor) Then
            Row("Proveedor") = Articulo.proveedor.ToString
            Dim tmp_proveedorarticulo As New cls_proveedorarticulo_
            If tmp_proveedorarticulo.BuscarUltimoXidarticuloXidproveedor(Articulo.idproveedor, Articulo.idarticulo) Then
                Row("Fecha costo") = tmp_proveedorarticulo.fecha.ToShortDateString
                Row("Moneda") = tmp_proveedorarticulo.moneda.ToString
            End If
        End If
        Row("Tipo costo") = EnumDescription(Articulo.tipocosto)

        dtt_componente_.Rows.Add(Row)
        'ulg_Lista.Rows(ulg_Lista.Rows.Count - 1).Height = 19
        Return Row
    End Function

    Public Sub ModificarItem(ByRef Articulo As cls_articulo_, ByRef ulg_row As DataRow, Optional ByVal prm_nivel2 As Boolean = False)
        ulg_row("Identificador (ID)") = Articulo.idarticulo
        ulg_row("Código") = Articulo.codigo
        ulg_row("Nombre") = Articulo.nombre
        ulg_row("Descripcion") = Articulo.descripcion
        ulg_row("Rubro") = Articulo.articulorubro.ToString
        ulg_row("En venta") = IIf(Articulo.enventa, "Sí", "No")
        ulg_row("Tipo") = Articulo.tipo
        ulg_row("Unidad") = Articulo.unidaddetalle.ToString
        ulg_row("Costo") = Articulo.unidaddetalle.CValCargar(Articulo.costo)
        ulg_row("Fecha costo") = ""
        ulg_row("Proveedor") = ""
        ulg_row("Moneda") = ""
        If Not IsNothing(Articulo.proveedor) Then
            ulg_row("Proveedor") = Articulo.proveedor.ToString
            Dim tmp_proveedorarticulo As New cls_proveedorarticulo_
            If tmp_proveedorarticulo.BuscarUltimoXidarticuloXidproveedor(Articulo.idproveedor, Articulo.idarticulo) Then
                ulg_row("Fecha costo") = tmp_proveedorarticulo.fecha.ToShortDateString
                ulg_row("Moneda") = tmp_proveedorarticulo.moneda.ToString
            End If
        End If
        ulg_row("Tipo costo") = EnumDescription(Articulo.tipocosto)

        If prm_nivel2 Then
            For Each row As DataRow In dtt_componente_.Rows
                If row("Identificador (ID)") = Articulo.idarticulo Then
                    ModificarItem(Articulo, row, True)
                    Exit For
                End If
            Next
        End If


    End Sub

    Public Sub New()

        Me.Cursor = Cursors.WaitCursor
        InitializeComponent()
        PERMISONuevo = "008001002"
        PERMISOModificar = "008001003"
        PERMISOEliminar = "008001004"
        PERMISOImprimir = "008001005"
        Me.Text = lbl_modulo.Text : lbl_modulodescripcion.Text = "Listado de " & lbl_modulo.Text & "."
        IniciarLista()
        Me.Cursor = Cursors.Default

    End Sub

    Private Sub chk_articulosenventa_CheckedChanged(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles chk_articulosenventa.ItemClick
        If chk_articulosenventa.Checked Then
            gdv_general.Columns("En venta").FilterInfo = New DevExpress.XtraGrid.Columns.ColumnFilterInfo("[En venta] = 'Sí'")
        Else
            gdv_general.Columns("En venta").ClearFilter()
        End If
    End Sub

    Private Sub chk_agruparportipo_CheckedChanged(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles chk_agruparportipo.ItemClick
        If chk_agruparportipo.Checked Then
            gdv_general.Columns("Tipo").Group()
            gdv_general.ExpandAllGroups()
        Else
            gdv_general.Columns("Tipo").UnGroup()
        End If
    End Sub

    Dim Filter As String = ""
    Public Overrides Sub gdv_general_FocusedRowChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs)
        If gdv_general.SelectedRowsCount > 0 Then
            gdv_componente_.ClearSelection()
            gdv_componente_.SelectRow(0)
            Filter = "[Identificador (ID)] = '0'"
            Dim Articulo As New cls_articulo_
            Articulo.Buscar(gdv_general.GetDataRow(gdv_general.GetSelectedRows(0))("Identificador (ID)"))
            lbl_Componente.Text = Articulo.ToString
            If btn_materiasPrimas.Text = "Materias primas" Then
                filtrarMateriasPrimas(Articulo, True)
            ElseIf btn_materiasPrimas.Text = "Dependencias" Then
                filtrarDependencias(Articulo)
            End If
            gdv_componente_.Columns("Identificador (ID)").FilterInfo = New DevExpress.XtraGrid.Columns.ColumnFilterInfo(Filter)
        End If
    End Sub
    Private Sub filtrarMateriasPrimas(ByRef prm_articulo As cls_articulo_, ByVal primero As Boolean)

        If prm_articulo.tipo = cls_articulo_.enu_tipo.Mprima Then
            If Not primero Then
                Filter &= "Or [Identificador (ID)] = '" & prm_articulo.idarticulo & "'"
            End If
        End If

        If Not IsNothing(prm_articulo.articulocomposicionarticulo_) Then
            If Not IsNothing(prm_articulo.articulocomposicionarticulo_.Items) Then
                For Each comp As cls_articulocomposicionarticulo_ In prm_articulo.articulocomposicionarticulo_.Items
                    filtrarMateriasPrimas(comp.articulo, False)
                Next
            End If
        End If
    End Sub

    Private Sub filtrarDependencias(ByRef prm_articulo As cls_articulo_)
        Dim tmp_articulocomposicionarticulo_ As New cls_articulocomposicionarticulo_
        If tmp_articulocomposicionarticulo_.CargarTodos() Then
            For Each composicion As cls_articulocomposicionarticulo_ In tmp_articulocomposicionarticulo_.Items
                If composicion.idarticulo = prm_articulo.idarticulo Then
                    Filter &= "Or [Identificador (ID)] = '" & composicion.idarticuloprimario & "'"
                End If
            Next
        End If
    End Sub

    Public Overrides Sub bbi_Eliminar_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs)
        If ComprobarPermiso(PERMISOEliminar) Then
            Try
                If gdv_general.SelectedRowsCount > 0 Then
                    If ErrManagerShow("000005", Me) = DialogResult.Yes Then
                        Dim eliminarRegistro As Boolean = False
                        If UsuarioLOG.esroot Then
                            If ErrManagerShow("001023", Me) = DialogResult.Yes Then
                                eliminarRegistro = True
                            End If
                        End If


                        Dim objeto As Object
                        objeto = Activator.CreateInstance(Type.GetType(Replace(Application.ProductName, " ", "_") & "." & Replace(Me.Name, "xtf_LISTADO", "cls_"), True, True))

                        If eliminarRegistro Then
                            objeto.Eliminar(gdv_general.GetDataRow(gdv_general.GetSelectedRows(0))("Identificador (ID)"))
                        Else
                            objeto.buscar(gdv_general.GetDataRow(gdv_general.GetSelectedRows(0))("Identificador (ID)"))
                            objeto.registro.idregistroestado = 2
                            objeto.modificar()
                        End If

                        dtt_DataTable.Rows.Remove(gdv_general.GetDataRow(gdv_general.GetSelectedRows(0)))
                        For Each row As DataRow In dtt_componente_.Rows
                            If row("Identificador (ID)") = gdv_general.GetDataRow(gdv_general.GetSelectedRows(0))("Identificador (ID)") Then
                                dtt_componente_.Rows.Remove(row)
                                Exit For
                            End If
                        Next
                    End If
                End If
            Catch ex As Exception
                'Dim frmError As New frm_ErrorManager(ex.Message)
            End Try
        End If

    End Sub

    Private Sub btn_materiasPrimas_Click(sender As System.Object, e As System.EventArgs) Handles btn_materiasPrimas.Click
        If btn_materiasPrimas.Text = "Dependencias" Then
            btn_materiasPrimas.Text = "Materias primas"
        Else
            btn_materiasPrimas.Text = "Dependencias"
        End If
        gdv_general_FocusedRowChanged(Nothing, Nothing)
    End Sub

    Private Sub chk_detalle__CheckedChanged(sender As System.Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles chk_detalle_.CheckedChanged
        If chk_detalle_.Checked Then
            gdc_componente_.Visible = True
            spc_general.Visible = True
            pnl_componente_.Visible = True
        Else
            gdc_componente_.Visible = False
            spc_general.Visible = False
            pnl_componente_.Visible = False
        End If
    End Sub
End Class